package com.ruoyi.ring.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.VoiceRecordStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ora.constant.BizConstants;
import com.ruoyi.ring.domain.RingVoiceRecord;
import com.ruoyi.ring.domain.VoiceSegment;
import com.ruoyi.ring.domain.VoiceTranModel;
import com.ruoyi.ring.factory.AiFactory;
import com.ruoyi.ring.mapper.RingVoiceRecordMapper;
import com.ruoyi.ring.service.IRingVoiceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 语音转写记录Service业务层处理
 * 
 * @author liuwp
 * @date 2025-10-24
 */
@Service
public class RingVoiceRecordServiceImpl implements IRingVoiceRecordService 
{
    @Autowired
    private RingVoiceRecordMapper ringVoiceRecordMapper;

    /**
     * 查询语音转写记录
     * 
     * @param id 语音转写记录主键
     * @return 语音转写记录
     */
    @Override
    public RingVoiceRecord selectRingVoiceRecordById(Long id)
    {
        return ringVoiceRecordMapper.selectRingVoiceRecordById(id);
    }

    /**
     * 查询语音转写记录列表
     * 
     * @param ringVoiceRecord 语音转写记录
     * @return 语音转写记录
     */
    @Override
    public List<RingVoiceRecord> selectRingVoiceRecordList(RingVoiceRecord ringVoiceRecord)
    {
        return ringVoiceRecordMapper.selectRingVoiceRecordList(ringVoiceRecord);
    }

    /**
     * 根据业务主键查询一条记录：语音转写记录
     *
     * @param ringVoiceRecord 语音转写记录
     * @return 语音转写记录
     */
    @Override
    public RingVoiceRecord selectOneRingVoiceRecord(RingVoiceRecord ringVoiceRecord)
    {
        return ringVoiceRecordMapper.selectOneRingVoiceRecord(ringVoiceRecord);
    }

    /**
     * 新增语音转写记录
     * 
     * @param ringVoiceRecord 语音转写记录
     * @return 结果
     */
    @Override
    public int insertRingVoiceRecord(RingVoiceRecord ringVoiceRecord)
    {
        ringVoiceRecord.setCreateTime(DateUtils.getNowDate());
        return ringVoiceRecordMapper.insertRingVoiceRecord(ringVoiceRecord);
    }

    /**
     * 修改语音转写记录
     * 
     * @param ringVoiceRecord 语音转写记录
     * @return 结果
     */
    @Override
    public int updateRingVoiceRecord(RingVoiceRecord ringVoiceRecord)
    {
        return ringVoiceRecordMapper.updateRingVoiceRecord(ringVoiceRecord);
    }

    @Override
    public int updateRingVoiceRecordCondition(RingVoiceRecord ringVoiceRecord, RingVoiceRecord ringVoiceRecordCondition)
    {
        return ringVoiceRecordMapper.updateRingVoiceRecordCondition(ringVoiceRecord, ringVoiceRecordCondition);
    }

    /**
     * 批量删除语音转写记录
     * 
     * @param ids 需要删除的语音转写记录主键
     * @return 结果
     */
    @Override
    public int deleteRingVoiceRecordByIds(Long[] ids)
    {
        return ringVoiceRecordMapper.deleteRingVoiceRecordByIds(ids);
    }

    /**
     * 删除语音转写记录信息
     * 
     * @param id 语音转写记录主键
     * @return 结果
     */
    @Override
    public int deleteRingVoiceRecordById(Long id)
    {
        return ringVoiceRecordMapper.deleteRingVoiceRecordById(id);
    }

    /**
     * 条件删除语音转写记录
     *
     * @param ringVoiceRecord 语音转写记录
     * @return 结果
     */
    @Override
    public int deleteRingVoiceRecordByCondition(RingVoiceRecord ringVoiceRecord)
    {
        return ringVoiceRecordMapper.deleteRingVoiceRecordByCondition(ringVoiceRecord);
    }

    @Override
    public void tranFinishHandle(RingVoiceRecord voiceRecord, VoiceTranModel voiceTranModel) {
        try {
            if (voiceTranModel != null && Constants.SUCCESS.equalsIgnoreCase(String.valueOf(voiceTranModel.getCode()))){
                // TODO 再次判断转写时长， 如果超出剩余时间则直接改为  OUT_OF_BALANCE  如果时长够用则把用户时间减掉

                /// TODO 扣除剩余转写时间
//                Long userId = SecurityUtils.getUserId();
//                SysUser user = userService.selectUserById(userId);
//                if (user != null){
//                    // 转写时长
//                    Long transDuration = Long.parseLong(voiceTranModel.getTotalDuration());
//                    // 剩余时长
//                    Long surplusDuration = user.getSurplusDuration();
//                    if (surplusDuration < transDuration){
//                        // 余额不足
//                        voiceRecord.setStatus(VoiceRecordStatus.OUT_OF_BALANCE.getValue());
//                        updateVoiceRecord(voiceRecord);
//                        return;
//                    }
//                    // 扣除时长
//                    user.setSurplusDuration(surplusDuration - transDuration);
//                    userService.updateUser(user);
//                }

                if (StringUtils.isNotEmpty(voiceTranModel.getText())){
                    voiceRecord.setVoiceContent(voiceTranModel.getText());
                    voiceRecord.setVoiceTransliterate(JSONObject.toJSONString(voiceTranModel));

                    // 标题
                    String title = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceRecord.getVoiceContent()+"。请给以上内容做一个10字左右的标题，直接返回结果即可。不要加任何其他内容");
                    String voiceTitle = title.contains("error")?voiceRecord.getVoiceContent().length()>10?voiceRecord.getVoiceContent().substring(0, 10):voiceRecord.getVoiceContent():title;
                    voiceRecord.setVoiceTitle(voiceTitle);

                    // 摘要
                    String summarize = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceRecord.getVoiceContent()+"。请给以上内容做一个20字左右的总结");
                    String voiceSummarize = summarize.contains("error")?voiceRecord.getVoiceContent().length()>20?voiceRecord.getVoiceContent().substring(0, 20):voiceRecord.getVoiceContent():summarize;
                    voiceRecord.setVoiceSummarize(voiceSummarize);

                    // 待办
                    String agency = AiFactory.build(BizConstants.AI_MODEL.getValue()).chatCompletions(voiceRecord.getVoiceContent()+"。请根据以为内容生成出待办的清单，把时间和事项分开，时间使用年月日格式，不要使用明天后天等格式，使用json格式输出，直接json格式就行，不需要加markdown格式，字段名使用英文，例如：{\"time\":\"明天\",\"thing\":\"陪父母去爬山\"}，如果没有合适的事项直接返回空，不要随便举例");
                    String voiceAgency = agency.contains("error")?null:agency;
                    voiceRecord.setVoiceAgency(voiceAgency);

                    try {
                        if (voiceTranModel.getSegments() != null && voiceTranModel.getSegments().size() > 0){
                            VoiceSegment lastItem = voiceTranModel.getSegments().get(voiceTranModel.getSegments().size() - 1);
                            Long roundedEnd = (long) Math.ceil(Double.valueOf(lastItem.getEnd()));
                            voiceRecord.setVoiceDuration(roundedEnd);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                voiceRecord.setStatus(VoiceRecordStatus.TRANSLATED.getValue());

            }else {
                voiceRecord.setStatus(VoiceRecordStatus.ERROR.getValue());
            }
        }catch (Exception e){
            e.printStackTrace();
            voiceRecord.setStatus(VoiceRecordStatus.ERROR.getValue());
        }
        updateRingVoiceRecord(voiceRecord);
    }
}
